package mirrormonkey.core.client;

import mirrormonkey.core.member.ConstructorData;
import mirrormonkey.core.messages.EntityInitMessage;
import mirrormonkey.framework.ClientSyncAppState;
import mirrormonkey.framework.entity.StaticEntityData;
import mirrormonkey.framework.entity.SyncEntity;

import com.jme3.network.Client;
import com.jme3.network.Message;
import com.jme3.network.MessageConnection;
import com.jme3.network.MessageListener;

public class EntityInitListener implements MessageListener<MessageConnection> {

	protected final ClientCoreModule module;

	protected final Client client;

	public EntityInitListener(ClientCoreModule module) {
		this.module = module;
		client = ((ClientSyncAppState) module.appState).client;
	}

	@Override
	public void messageReceived(MessageConnection source, Message message) {
		try {
			EntityInitMessage castMessage = (EntityInitMessage) message;
			Class<? extends SyncEntity> entityClass = (Class<? extends SyncEntity>) Class
					.forName(castMessage.className);
			Class<? extends SyncEntity> connectedClass = (Class<? extends SyncEntity>) Class
					.forName(castMessage.connectedClassName);
			StaticEntityData staticData = module.getEntityProvider()
					.getStaticData(entityClass, connectedClass);

			ConstructorData constr = staticData.getData(castMessage.constrId,
					ConstructorData.class);
			SyncEntity reference = constr.newEntity(castMessage.packedParams);

			ClientEntityData data = module.getData(castMessage.entityId);
			System.out.println("INIT LISTENER:");
			data.referenceArrived(reference, staticData);
			if (!module.getData(source).isRunning()) {
				module.getData(source).setRunning(true);
			}

			module.notifyInitListeners(data, data.getStaticData(source),
					module.connectionInfo);
		} catch (RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
